home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11158 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  51 lines

  1. Path: ip-pdx09-31.teleport.com!user
  2. From: peteski@teleport.com (Peter Miller)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Global variables in a multiple-sourcefile application
  5. Date: Thu, 21 Mar 1996 22:20:58 -0700
  6. Organization: Teleport - Portland's Public Access (503) 220-1016
  7. Message-ID: <peteski-2103962220580001@ip-pdx09-31.teleport.com>
  8. References: <827255412.29892.0@fersys.demon.co.uk>
  9. NNTP-Posting-Host: ip-pdx09-31.teleport.com
  10.  
  11. In article <827255412.29892.0@fersys.demon.co.uk>, mlb@fersys.demon.co.uk wrote:
  12.  
  13. > I have two questions about the use of global variables in a 
  14. > multiple-sourcefile application:
  15. > 1) If I have a global variable x that is used in both source files of
  16. > an application, but I don't need it initialised in its definition,
  17. > I would generally put "int x;" in one and "extern int x;" in the other.
  18. > However, is there anything unsafe about putting a declaration in a header 
  19. > file included by both files, without a definition in either file, or
  20. > do I really need a definition in one of the files?
  21. > i.e. is this OK?:
  22. > Mark Bergman                       Email: mlb@fersys.co.uk
  23. > Ferranti Syseca Ltd.               Tel:   0161-946 7178
  24. > Wythenshawe, Manchester, UK        Fax:   0161-946 7001
  25.  
  26.  
  27. 1) I would expect that the modules would compile but would not link together.
  28. No, you are going to have to define the variable in one file, and declare
  29. it extern in the other file, otherwise the linker will not create an
  30. executable.
  31.  
  32. so, typically, in the main module you would define the variable:
  33.    int x;
  34. and in the other module, declare it:
  35.     extern int x;
  36.  
  37. 2) It is very dangerous to have data with the same name declared
  38. differently between source files.  If the actual variable is smaller than
  39. the external declaration, then use of that variable externally will likely
  40. cause memory reads and writes out of bounds.  If the actual variable is of
  41. a larger size than the external declaration, then unexpected values are
  42. likely to result.  In either case, doom and aggravation are the most
  43. likely result.
  44.  
  45. Sincerely,
  46.  
  47. Peter Miller
  48.